<template>
  <div class="login-container" @mousedown="mousedown">
    <!-- 自定义工具栏 -->
    <div class="custom-toolbar">
      <el-button class="close-btn" @click="closeWindow">
        X
      </el-button>
    </div>
    <!-- 顶部欢迎词 -->
    <div class="welcome-section">
      <h1>欢迎访问iBear客户端</h1>
      <p>请登录您的账号继续操作</p>
    </div>

    <!-- 登录表单 -->
    <el-card class="login-box" shadow="hover">
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" @keyup.enter="handleLogin">
        <!-- 账号 -->
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入账号" prefix-icon="User" clearable size="large" />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" placeholder="请输入密码" prefix-icon="Lock" show-password size="large" />
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input v-model="loginForm.captcha" placeholder="请输入验证码" prefix-icon="Key" size="large"
              class="captcha-input" />
            <div class="captcha-image" @click="refreshCaptcha">
              <img :src="captchaUrl" alt="验证码" />
            </div>
          </div>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading" size="large" class="login-btn">
            登 录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 底部版权声明 -->
    <div class="footer">
      <p>© 2025 版权所有 | iBear客户端 {{ version }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type FormInstance } from 'element-plus'
import router from '@router/index'
import { getUUID } from '@utils/index'
import { loginSys, getCaptchaImage } from '@api/login'
import { useUserStore } from '@store/useUserStore';
import { CURRENT_VERSION } from '@utils/version';
import { useSettingStore } from '@store/settingStore';


const version = ref(CURRENT_VERSION);

// 表单数据类型定义
interface DataForm {
  username: string
  password: string
  uuid: string
  captcha: string
}

// 表单校验规则类型定义
interface DataRule {
  username: Array<{ required: boolean; message: string; trigger: string }>
  password: Array<{ required: boolean; message: string; trigger: string }>
  captcha: Array<{ required: boolean; message: string; trigger: string }>
}

// 表单数据响应式对象
const loginForm = reactive<DataForm>({
  username: '',
  password: '',
  uuid: '',
  captcha: ''
})

// 表单校验规则
const loginRules = ref<DataRule>({
  username: [
    { required: true, message: '帐号不能为空', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '验证码不能为空', trigger: 'blur' }
  ]
})

// 表单引用
const loginFormRef = ref<FormInstance>()


// 加载状态
const loading = ref(false)

// 刷新验证码
const refreshCaptcha = () => {
  getCaptcha()
}
/**
 * 获取验证码
 */
let captchaUrl = ref<string>('');
const getCaptcha = async () => {
  const uuid: string = getUUID();
  loginForm.uuid = uuid;
  let res = await getCaptchaImage({ uuid })
  let blob = new Blob([res], { type: 'application/vnd.ms-excel' });
  let imgUrl = URL.createObjectURL(blob);
  captchaUrl.value = imgUrl;
}

/**
 * 表单提交处理
 */
// 登录方法
const handleLogin = async () => {
  if (!loginFormRef.value) return;

  try {
    await loginFormRef.value.validate(); // 表单验证
    loading.value = true;

    // 发送登录请求
    const res = await loginSys({
      username: loginForm.username,
      password: loginForm.password,
      uuid: loginForm.uuid,
      captcha: loginForm.captcha,
    });
    if (res.code == '0') {
      // 1. 存储 token 到 cookie
      // Cookies.set('token', res.token)
      // Cookies.set('username', loginForm.username)
      localStorage.setItem('token', res.token);
      localStorage.setItem('username', loginForm.username);
      // 2. 获取用户信息用于头像展示（后续使用）
      await useUserStore().getUserInfo();
      // 3. 跳转首页
      router.push('/home');
      // 4. 调用 Electron API 修改窗口属性，这里一并确认是否存在默认的存储路径
      // let setSavePaht = settings.value.general.savePath;
      // if(setSavePaht == null || setSavePaht.trim() == ''){
      //   setSavePaht = savePath;
      // }
      // window.electron.ipcRenderer.invoke('init-savePath',setSavePaht);
      window.electron.ipcRenderer.invoke('home-window');
    } else {
      ElMessage.error(res.msg || '登录失败');
      getCaptcha(); // 刷新验证码
    }
  } catch (error) {
    ElMessage.error('登录失败，请重试');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  // 页面加载时获取验证码
  getCaptcha()
  // 初始化设置
  useSettingStore().initSettings()
})

let isKeyDown = ref<boolean>(false);
let dinatesX = ref<number>(0);
let dinatesY = ref<number>(0);

const mousedown = (event) => {
  isKeyDown.value = true;
  dinatesX.value = event.x;
  dinatesY.value = event.y;

  document.onmousemove = (ev) => {
    if (isKeyDown.value) {
      const x = ev.screenX - dinatesX.value;
      const y = ev.screenY - dinatesY.value;
      //给主进程传入坐标
      let data = {
        appX: x,
        appY: y
      }
      window.electron.ipcRenderer.invoke('custom-adsorption', data);
    }
  };
  document.onmouseup = () => {
    isKeyDown.value = false
  };
}

// 关闭窗口按钮事件处理函数
const closeWindow = () => {
  window.electron.ipcRenderer.invoke('close-window');
}
</script>

<style scoped>
.custom-toolbar {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 99999;
}

.close-btn {
  width: 30px;
  height: 30px;
  padding: 0;
  background-color: transparent;
  border: none;
  color: white;
  font-size: 16px;
  transition: all 0.3s ease;
}

.close-btn:hover {
  color: #ff4d4f;
  transform: scale(1.1);
}

.login-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  width: 100vw;
  height: 100vh;
  padding: 0px;
  box-sizing: border-box;
  background-color: #2c3e50;
  border-radius: 10px;
}

.welcome-section {
  text-align: center;
  margin-bottom: 40px;
  color: white;
}

.welcome-section h1 {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 10px;
}

.welcome-section p {
  font-size: 16px;
  color: #7a8ca5;
}

.login-box {
  width: 100%;
  max-width: 420px;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  background: white;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-input {
  flex: 1;
}

.captcha-image {
  width: 150px;
  height: 40px;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.captcha-image:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.login-btn {
  width: 100%;
  margin-top: 10px;
  height: 46px;
  font-size: 16px;
  letter-spacing: 8px;
}

.footer {
  margin-top: 80px;
  text-align: center;
  color: white;
  font-size: 14px;
}
</style>